<?php

class fvImport {

	protected static $LoggedSessionId = null;
	protected static $client = null;

	public static function initilize() {
		self::$client = new SoapClient(fvSite::$fvConfig->get('path.wsdl'),array(
            "trace"      => 1, 
            "exceptions" => 1));
	}

	public static function Login() {
		if (!self::$client) self::initilize();

		$parameters = array();
		$parameters[0]['login'] = fvSite::$fvConfig->get('webservice.login');
		$parameters[0]['password'] = fvSite::$fvConfig->get('webservice.password');
		$parameters[0]['siteName'] = fvSite::$fvConfig->get('server_name');
		$parameters[0]['loginAcl'] = fvSite::$fvConfig->get('webservice.login_acl');

		$responce = self::$client->__call('doLogin', $parameters);
		self::$LoggedSessionId = $responce['LoggedSessionId'];

		return $responce;
	}

	public static function getRubricList() {
		if (!self::$LoggedSessionId) self::Login();

		if (!$last_update = RubricManager::getInstance()->getLastUpdateDate()) {
			$last_update = fvSite::$fvConfig->get('webservice.init_date');
		}

		$parameters = array();
		$parameters[0]['LastUpdateDate'] = $last_update;
		$parameters[0]['LoggedSessionId'] = self::$LoggedSessionId;

		$responce = self::$client->__call('doGetRubrics', $parameters);

		if (!is_array($responce->Result)) $responce->Result = array($responce->Result);

		foreach ($responce->Result as $object) {
			self::addImportedObject("Rubric", $object);
		}
		 
		return true;
	}

	public static function getNewsList() {
		if (!self::$LoggedSessionId) self::Login();

		//        @todo - fix last update date retrieve

		//if (!$last_update = Manager::getInstance()->getLastUpdateDate()) {
		$last_update = fvSite::$fvConfig->get('webservice.init_date');
		//}

		$parameters = array();
		$parameters[0]['LastUpdateDate'] = $last_update;
		$parameters[0]['LoggedSessionId'] = self::$LoggedSessionId;
		$parameters[0]['RubricList'] = null;
		$parameters[0]['CountryList'] = null;
		try{
			$responce = self::$client->__call('doGetNews', $parameters);
		} catch (Exception $e) {

		}
		
		if (!is_array($responce->Result)) $responce->Result = array($responce->Result);

		foreach ($responce->Result as $object) {
			self::addImportedObject("News", $object);
		}
		 
		return true;
	}

	protected static function addImportedObject($objectType, $objectData) {
		$IOs = ImportedObjectManager::getInstance()->getAll("object_id = ? AND object_name = ?", null, null, array($objectData->id, $objectType));
		if (count($IOs) == 1) {
			$ImportedObject = $IOs[0];
		} else {
			$ImportedObject = new ImportedObject();
		}

		$ImportedObject['object_id'] = $objectData->id;
		$ImportedObject['object_name'] = $objectType;
		$ImportedObject['blob_data'] = $objectData->blobData;
		$ImportedObject['object_hash'] = $objectData->objectHash;

		$ImportedObject->save();
	}

}

?>